package grimbo.goodwinfooty.server.mvc;

import grimbo.goodwinfooty.server.GoodwinFootyDB;
import grimbo.goodwinfooty.service.model.FootyMatrix;

import java.io.PrintWriter;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

/**
 * Outputs the FootyMatrix as JSONP.
 */
public class FootyMatrixJSONPController extends AbstractController {
	private static final String CNAME = FootyMatrixJSONPController.class
			.getName();
	private static final Logger log = Logger.getLogger(CNAME);
	private static final String PARAM_FUNCTION_NAME = "f";

	private GoodwinFootyDB datastore;

	@Override
	protected ModelAndView handleRequestInternal(HttpServletRequest req,
			HttpServletResponse res) throws Exception {
		final String MNAME = "getXlsFileBytes(HttpServletRequest)";
		final boolean DEBUG = log.isLoggable(Level.FINE);

		if (DEBUG) {
			log.entering(CNAME, MNAME);
		}

		String f = req.getParameter(PARAM_FUNCTION_NAME);

		res.setContentType("text/javascript");
		PrintWriter w = res.getWriter();

		FootyMatrix fm = datastore.loadFootyMatrix();

		if (null != fm) {
			JSONObject jsonObject = (JSONObject) JSONSerializer.toJSON(fm);
			if (null != f) {
				w.print(f);
				w.print("(");
			}
			w.print(jsonObject);
			if (null != f) {
				w.print(")");
			}
		}

		if (DEBUG) {
			log.exiting(CNAME, MNAME);
		}

		return null;
	}

	public GoodwinFootyDB getDatastore() {
		return datastore;
	}

	public void setDatastore(GoodwinFootyDB datastore) {
		this.datastore = datastore;
	}
}
